package com.du.yuchenweather.util;

import android.text.TextUtils;

import com.du.yuchenweather.util.db.City;
import com.du.yuchenweather.util.db.Country;
import com.du.yuchenweather.util.db.Province;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

public class Utility {
    /**
     * @param responce
     * @return 省资源解析
     */
    public static boolean handleProvinceResponce(String responce) {
        if (!TextUtils.isEmpty(responce)) {
            try {
                JSONArray allProvinceJa = new JSONArray(responce);
                for (int i = 0; i < allProvinceJa.length(); i++) {
                    JSONObject provinceObj = allProvinceJa.getJSONObject(i);
                    Province province = new Province();
                    province.setProvinceName(provinceObj.getString("name"));
                    province.setProvinceCode(provinceObj.getInt("id"));
                    province.save();
                }
                return true;
            } catch (JSONException e) {
                e.printStackTrace();
            }
        }
        return false;
    }

    /**
     *
     * @param responce
     * @param provinceId
     * @return
     * 市资源解析
     */
    public static boolean handleCityResponce(String responce, int provinceId) {
        if (!TextUtils.isEmpty(responce)) {
            try {
                JSONArray allCityJa = new JSONArray(responce);
                for (int i = 0; i < allCityJa.length(); i++) {
                    JSONObject cityObj = allCityJa.getJSONObject(i);
                    City city = new City();
                    city.setCityName(cityObj.getString("name"));
                    city.setCityCode(cityObj.getInt("id"));
                    city.setProvinceId(provinceId);
                    city.save();
                }
                return true;
            } catch (JSONException e) {
                e.printStackTrace();
            }
        }
        return false;
    }

    /**
     *
     * @param responce
     * @param cityId
     * @return
     * 区资源解析
     */
    public static boolean handleCountryResponce(String responce, int cityId) {
        if (!TextUtils.isEmpty(responce)) {
            try {
                JSONArray allCountryJa = new JSONArray(responce);
                for(int i = 0; i < allCountryJa.length(); i++) {
                    JSONObject countryObj = allCountryJa.getJSONObject(i);
                    Country country = new Country();
                    country.setCountryName(countryObj.getString("name"));
                    country.setCountryCode(countryObj.getInt("id"));
                    country.setCityId(cityId);
                    country.save();
                }
                return true;
            } catch (JSONException e) {
                e.printStackTrace();
            }
        }
        return false;
    }

}
